package com.bgy.config.jwt;

import com.bgy.common.exception.CommonException;
import com.bgy.common.util.ResultUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;

@SuppressWarnings("SpringJavaAutowiringInspection")
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    Log log = LogFactory.getLog(JwtAuthenticationTokenFilter.class);


    @Qualifier("jwtUserDetailsServiceImpl")
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.header}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        String authHeader = request.getHeader("Auth");
        // log.info("处理后authHeader:" + authHeader);
        if (authHeader != null && authHeader.startsWith("Bearer")) {

            final String authToken = authHeader.substring(tokenHead.length() - 2); // The part after

            try {
                String username = jwtTokenUtil.getUsernameFromToken(authToken);
                if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

                    // 如果我们足够相信token中的数据，也就是我们足够相信签名token的secret的机制足够好
                    // 这种情况下，我们可以不用再查询数据库，而直接采用token中的数据
                    // 本例中，我们还是通过Spring Security的 @UserDetailsService 进行了数据查询
                    // 但简单验证的话，你可以采用直接验证token是否合法来避免昂贵的数据查询
                    JwtUser userDetails = (JwtUser) this.userDetailsService.loadUserByUsername(username);

                    if ((Boolean) jwtTokenUtil.validateToken(authToken, userDetails.getLoginId())) {
                        Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
                        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                                userDetails, null, authorities);
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                        SecurityContextHolder.getContext().setAuthentication(authentication);
                    }
                }
            } catch (CommonException exception) {
                ResultUtil.printWriter(response, exception.getCode(), exception.getMessage());
                return;
            }

        }
        chain.doFilter(request, response);
    }
}
